package com.fyl.leetcode.dynamic;

/**
 * @author:fyl
 * @date 2021/8/2 9:21
 * @Modified By:
 * @Modified Date:
 * @Description: 64
 * 给定一个包含非负整数的 mxn网格grid ，请找出一条从左上角到右下角的路径，使得路径上的数字总和为最小。
 * 说明：每次只能向下或者向右移动一步。
 * 示例 1：
 * 输入：grid = [[1,3,1],[1,5,1],[4,2,1]]
 * 输出：7
 * 解释：因为路径 1→3→1→1→1 的总和最小。
 */
public class MinimumPathSum {
    public static int minPathSum(int[][] grid) {
        int[][] states = new int[grid.length][grid[0].length];
        int sum = 0;
        //初始化第一行
        for (int i = 0; i < grid[0].length; i++) {
            sum += grid[0][i];
            states[0][i] = sum;
        }
        sum = 0;
        //初始化第一列
        for (int i = 0; i < grid.length; i++) {
            sum += grid[i][0];
            states[i][0] = sum;
        }
        for (int i = 1; i < grid.length; i++) {
            for (int j = 1; j < grid[0].length; j++) {
                states[i][j] = Math.min(states[i - 1][j] + grid[i][j], states[i][j - 1] + grid[i][j]);
            }
        }
        return states[states.length - 1][states[0].length - 1];
    }

    /**
     * 使用一维数组的方法
     * @param grid
     * @return
     */
    public int minPathSum2(int[][] grid) {
        if (grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int m = grid.length, n = grid[0].length;
        int[] dp = new int[n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (j == 0) {
                    dp[j] = dp[j];        // 只能从上侧走到该位置
                } else if (i == 0) {
                    dp[j] = dp[j - 1];    // 只能从左侧走到该位置
                } else {
                    dp[j] = Math.min(dp[j - 1], dp[j]);
                }
                dp[j] += grid[i][j];
            }
        }
        return dp[n - 1];
    }

    public static void main(String[] args) {
        int[][] grid = {{1,2,3},{4,5,6}};
        System.out.println(minPathSum(grid));
    }
}
